package com.yangkunhong.utils;

import com.google.gson.Gson;
import com.yangkunhong.constant.ErrMsg;
import com.yangkunhong.pojo.PageDataResponse;
import com.yangkunhong.pojo.ResponseData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JSONUtils {
    public static String parseJsonInputStream(HttpServletRequest req) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = req.getInputStream();
            if (inputStream != null) {
                // 指定字符编码为UTF-8
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    // 通常在这里不会重新抛出异常，而是记录日志或采取其他恢复措施
                    // throw ex; // 不建议在这里重新抛出异常，因为它会覆盖原始的IOException
                }
            }
        }
        String json = stringBuilder.toString();
        return json;
    }

    public static void sendJsonStr(ErrMsg errMsg, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        ResponseData responseData = new ResponseData();
        responseData.setCode(errMsg.getCode());
        responseData.setMessage(errMsg.getMessage());
        resp.getWriter().print((new Gson()).toJson(responseData));
        resp.getWriter().close();

    }

    public static void sendJsonStr(PageDataResponse pageDataResponse, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print((new Gson()).toJson(pageDataResponse));
        resp.getWriter().close();

    }
}
